package matchthreegame.schedulerTasks;

import java.util.ArrayList;

import com.smartfoxserver.v2.entities.SFSUser;

import matchthreegame.extensions.MatchThreeGameZoneExtension;
import matchthreegame.utils.WaitingList;

public class AutoCreateGamesTask implements Runnable {

	private MatchThreeGameZoneExtension zoneExtension;
	
	public AutoCreateGamesTask(MatchThreeGameZoneExtension extension) {
		
		this.zoneExtension = extension;
		
	}//Pesho e kelesh
	
	@Override
	public void run() {
		
		try {
    		WaitingList waitingPlayers = new WaitingList(zoneExtension.getWaitingList().getUsers());
    		zoneExtension.trace("WAITING USERS: " + waitingPlayers.getNumberWaiting());

    		if ( waitingPlayers.getUsers().size() >= 1 ) {
    			//start making game
    			zoneExtension.trace("Should start game");
        		
    			//We need even count of users to make games so we eliminate the odd one and set him against bot
        		if ( (waitingPlayers.getNumberWaiting() % 2) != 0 ) {
        			SFSUser playerToPlayWithBot = (SFSUser) waitingPlayers.remove(waitingPlayers.getUsers().get(waitingPlayers.getNumberWaiting() - 1).getId());
        			ArrayList<Integer> id = new ArrayList<Integer>();
        			id.add(playerToPlayWithBot.getId());
        			zoneExtension.startGame(id);
        		}
        		zoneExtension.trace("Should create " + waitingPlayers.getNumberWaiting() / 2 + " rooms");
        		        		
        		// Array contains Rooms with players
        		ArrayList<ArrayList<Integer>> roomsArray = new ArrayList<ArrayList<Integer>>();
        		
        		for (int i = 0; i < waitingPlayers.getNumberWaiting(); i += 2) {
        			
        			// Array contains Players for Room
	    			ArrayList<Integer> roomPlayers = new ArrayList<Integer>();
	    			roomPlayers.add(waitingPlayers.getUsers().get(i).getId());
	    			roomPlayers.add(waitingPlayers.getUsers().get(i+1).getId());
	    			roomsArray.add(roomPlayers);
	    			
	    		}
        		
        		// Start game for each Room with players in it
        		for (int i = 0; i < roomsArray.size(); i++) {
        			ArrayList<Integer> roomPlayers = roomsArray.get(i);
        			zoneExtension.startGame(roomPlayers);
				}
    			
    		} else {
    			zoneExtension.trace("Not Enough Players To Start Game");
    		}
    		
    	} catch (Exception e) {
    		e.printStackTrace();
		}

	}

}
